import {HTTP} from '../util/http.js'
class ClassicModel extends HTTP{
  getLatest(sCallback){
    this.request({
      url: 'classic/latest',
      success: (res) => {
        sCallback(res)
        this._setLatestIndex(res.index)
        let key = this._getKey(res.index)
        wx.setStorageSync(key, res)
      }
    })
  }

  // 获取期刊函数
  getClassic(index, nextOrPrevious, sCallback) {
    // 缓存中寻找期刊数据，若缓存中不存在，则向后台请求
    // 若缓存中存在，则不发送请求，使用缓存数据
    let key = nextOrPrevious === 'next' ? 
        this._getKey(index+1) : this._getKey(index-1)
    let classic = wx.getStorageSync(key)
    if(!classic) {
      this.request({
        url: `classic/${index}/${nextOrPrevious}`,
        success: res => {
          wx.setStorageSync(this._getKey(res.index), res)
          sCallback(res)
        }
      })
    }else {
      sCallback(classic) // 返回缓存数据
    } 
    
  }

  isFirst(index) {
    return index === 1 ? true : false
  }

  isLatest(index) {
    let latestIndex = this._getLatestIndex()
    return latestIndex == index ? true : false
  }

  getMyFavor(success) {
    const params = {
      url: 'classic/favor',
      success: success
    }
    this.request(params)
  }

  _setLatestIndex(index) { // 写入缓存
    wx.setStorageSync('latest', index) // 同步写入缓存，去掉sync为异步写入缓存
    // 如果非常追求性能，可使用异步写入缓存，如果写入的数据量较小，建议使用同步写入
  }
  
  _getLatestIndex() { // 获取缓存
    let index = wx.getStorageSync('latest')
    return index 
  }

  // 设置缓存key
  _getKey(index) {
    let key = 'classic' + index
    return key
  }
}
export { ClassicModel }